package com.bw.repair.view

import android.app.Activity
import android.content.Intent
import androidx.appcompat.app.AppCompatActivity
import android.os.Bundle
import android.view.View
import androidx.recyclerview.widget.GridLayoutManager
import androidx.recyclerview.widget.LinearLayoutManager
import com.alibaba.android.arouter.facade.annotation.Autowired
import com.alibaba.android.arouter.facade.annotation.Route
import com.alibaba.android.arouter.launcher.ARouter
import com.blankj.utilcode.util.ToastUtils
import com.bw.base.constants.ApiConst
import com.bw.base.constants.RoutePath
import com.bw.base.constants.UserConst
import com.bw.common.view.BaseMvvmActivity
import com.bw.image.GlideImageLoader
import com.bw.repair.R
import com.bw.repair.adapter.ImageAdapter
import com.bw.repair.databinding.ActivityAddRepairBinding
import com.bw.repair.entity.RepairEntity
import com.bw.repair.net.RepairViewModel
import com.tencent.mmkv.MMKV
import com.wildma.pictureselector.PictureBean
import com.wildma.pictureselector.PictureSelector
import java.io.File
import java.text.SimpleDateFormat
import kotlin.random.Random

/**
 * 智慧园区-06-物业报修V1.1
 * 报修登记
 * 兰宏宇
 * 20250511
 */
@Route(path = RoutePath.PATH_ADD_REPAIR)
class AddRepairActivity : BaseMvvmActivity<ActivityAddRepairBinding, RepairViewModel>() {

    @Autowired
    lateinit var repairEntity: RepairEntity
    private val sdf = SimpleDateFormat("yyyy-MM-dd HH:mm:ss")
    private var uid:Int = -1

    private lateinit var imageAdapter: ImageAdapter
    private val imageUpLoadList:MutableList<String> = mutableListOf()

    override fun initView() {

        uid = MMKV.defaultMMKV().decodeInt(UserConst.USER_ID)
        binding.bar.ivBack.setOnClickListener { finish() }
        binding.bar.tvTitle.text = "报修登记"
        binding.etName.setText(repairEntity.repairName)
        binding.etDesc.setText(repairEntity.faultDescription)
        binding.etPhone.setText(repairEntity.contactMethod)
        binding.etLocation.setText(repairEntity.repairLocation)

        imageAdapter = ImageAdapter()
        if(repairEntity.faultPhotos.isNotEmpty()){
            imageAdapter.data.add(repairEntity.faultPhotos)
        }
        imageAdapter.data.add("初始")
        binding.rvImg.adapter = imageAdapter
        binding.rvImg.layoutManager = GridLayoutManager(this,4)


        imageAdapter.setOnItemClickListener { adapter, view, position ->
            val item = imageAdapter.data[position]
            if(item=="初始"){
                PictureSelector.create(this,103).selectPicture()
            }else{
                imageAdapter.removeAt(position)
            }
        }


        binding.tvSubmit.setOnClickListener {
            val name = binding.etName.text.toString()
            val desc = binding.etDesc.text.toString()
            val phone = binding.etPhone.text.toString()
            val location = binding.etLocation.text.toString()


            if (name == "" || desc == "" || phone == "" || location == "") {
                ToastUtils.showShort("请先输入内容")
            }

            repairEntity.repairName = name
            repairEntity.faultDescription = desc
            repairEntity.contactMethod = phone
            repairEntity.repairLocation = location
            if(repairEntity.processingStatus==""){
             repairEntity.processingStatus = "待处理"
            }
            repairEntity.repairTime = sdf.format(System.currentTimeMillis())
            if(repairEntity.orderNumber==""){
                repairEntity.orderNumber = "WX${Random.nextDouble(10000.00,100000.00).toInt()}"
            }

            vm.postRepair(repairEntity)


        }

    }

    override fun onCreate(savedInstanceState: Bundle?) {
        ARouter.getInstance().inject(this)
        super.onCreate(savedInstanceState)
    }

    override fun initData() {
        vm.postRepairSuccess.observe(this){
            ToastUtils.showShort("提交成功")
            finish()
        }

        vm.uploadFileSuccess.observe(this){
            //http://10.161.9.80:2207/images/mm/437/%E5%9B%BE%E7%89%871.png
            val regex = Regex("[a-f0-9]{32}\\.\\w+")  // 匹配 32 位哈希值 + 扩展名
            val fileName = regex.find(it)?.value ?: ""
            val str = "${ApiConst.BASE_URL}/images/module_repair/${uid}/${fileName}"
            imageUpLoadList.add(str)
            repairEntity.faultPhotos = str
        }
    }


    override fun onActivityResult(requestCode: Int, resultCode: Int, data: Intent?) {
        super.onActivityResult(requestCode, resultCode, data)
        if(requestCode==103&&resultCode== Activity.RESULT_OK){
            val pictureBean = data?.extras?.get(PictureSelector.PICTURE_RESULT) as PictureBean
            addImage(pictureBean.path)
        }
    }


    fun addImage(path:String){
        var index = imageAdapter.data.size - 1
        index = if(index>=0) index else 0
        imageAdapter.data.add(index,path)
        showAdd()
        vm.uploadFile(File(path),"module_repair",uid.toString())
        imageAdapter.notifyDataSetChanged()
    }

    fun showAdd(){
        if(imageAdapter.data.size>0){
            val llImg =
                imageAdapter.getViewByPosition(imageAdapter.data.size - 1, R.id.ll_img)
            if(imageAdapter.data.size>=5){
                llImg?.visibility =View.GONE
            }else{
                llImg?.visibility =View.VISIBLE
            }
        }

    }




}